const express = require('express');
const session = require('express-session');
const cors = require('cors');
const app = express();

// 配置CORS
const corsOptions = {
  origin: function(origin, callback) {
    const allowedOrigins = [
      'http://localhost:8080',
      'http://127.0.0.1:8080',
      'https://shaoermofangzhandui.asia',
      'http://shaoermofangzhandui.asia',
      'https://www.shaoermofangzhandui.asia',
      'http://www.shaoermofangzhandui.asia' 
    ];
    // 允许没有origin的请求（比如移动端APP）
    console.log('[CORS] 请求Origin:', origin);
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      console.log('[CORS] 允许跨域:', origin);
      callback(null, true);
    } else {
      console.warn('[CORS] 拒绝跨域:', origin);
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
};

app.use(cors(corsOptions));
app.use("/static",express.static('static'));

// 配置session
app.use(session({
  secret: 'your_session_secret',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: false } // 设置为 true，要求在 HTTPS 环境下使用 Cookie
}));

// 添加中间件来解析请求体
app.use(express.json());
app.use((req, res, next) => {
  console.log(`[Request] ${req.method} ${req.originalUrl}`);
  next();
});

const userApi = require('./userApi');
const  addressApi = require('./addressApi')
const goodsApi = require('./goodsApi')
const imgApi = require("./imgApi")
const orderApi = require("./orderApi")
const router = express.Router();
const path = require('path');

// 使用用户API路由
app.use('/api/user', userApi);
app.use('/api/address',addressApi)
app.use('/api/imglist',imgApi)
app.use('/api/goods',goodsApi)
app.use('/api/order',orderApi)

// 启动服务器
const port = 3000;
app.listen(port, () => {
  console.log(`服务器已启动，正在监听端口 ${port}`);
});
